package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.User;
import com.itheima.service.MemberService;
import com.itheima.service.UserService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;
    @Reference
    private UserService userService;

    @RequestMapping("/pageQuery")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = null;
        try {
            pageResult = memberService.findPage(queryPageBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageResult;
    }

    @RequestMapping("/add")
    public Result add(String userId, @RequestBody Member member) {
        try {
            if(userId!=null&&!userId.equals(userId)){
                member.setUser_Id(Integer.valueOf(userId));
            }
            memberService.add(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
    }

    //查询角色为健康管理师的用户
    @RequestMapping("/findAllUser")
    public Result findAllUser() {
        try {
            List<User> list = userService.findAllUser();
            return new Result(true, MessageConstant.QUERY_HEALTH_MANAGER_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_HEALTH_MANAGER_FAIL);
        }
    }

    @RequestMapping("/findById")
    public Result findById(String id) {
        try {
            Member member = memberService.findById(id);
            return new Result(true, MessageConstant.QUERY_MEMBER_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_HEALTH_MANAGER_FAIL);
        }
    }

    @RequestMapping("/edit")
    public Result edit(String userId, @RequestBody Member member) {
        try {
            if (userId != null && userId.length() > 0) {
                member.setUser_Id(Integer.valueOf(userId));
            }
            memberService.edit(member);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    @RequestMapping("/delete")
    public Result delete(String id) {
        try {
            memberService.deleteById(id);
            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                return new Result(false, e.getMessage());
            } else {
                e.printStackTrace();
                return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
            }
        }
    }

    @RequestMapping("/getMembersData")
    public Result getMemberData(@RequestBody List<Member> memberList, HttpServletRequest request) {
        try {
            List<Map> list = memberService.getMemberData(memberList);
            request.getSession().setAttribute("list", list);
            return new Result(true, MessageConstant.GET_MEMBER_DATA_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_DATA_FAIL);
        }
    }

    @RequestMapping("/exportMemberReport")
    public Result exportMemberReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            //获取模板文件所在目录
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "member_template.xlsx";
            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            List<Map> list = (List<Map>) request.getSession().getAttribute("list");
            //行数
            int rowNum = 1;
            for (Map map : list) {
                String name = (String) map.get("name");
                String sex = (String) map.get("sex");
                String phoneNumber = (String) map.get("phoneNumber");
                String address = (String) map.get("address");
                String setmealName = (String) map.get("setmealName");

                String checkGroupNames = (String) map.get("checkGroupNamess");
                String checkItemNames = (String) map.get("checkItemNamess");

                //获得第二行
                XSSFRow row = sheet.getRow(rowNum);
                if (row == null) {
                    row = sheet.createRow(rowNum);
                }
                ;
                row.createCell(0).setCellValue(name);
                row.createCell(1).setCellValue(sex);
                row.createCell(2).setCellValue(phoneNumber);
                row.createCell(3).setCellValue(address);
                row.createCell(4).setCellValue(setmealName);
                row.createCell(5).setCellValue(checkGroupNames);
                row.createCell(6).setCellValue(checkItemNames);
                rowNum++;
            }
            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型

            String filename = "会员信息.xlsx";
            filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
            response.setHeader("content-Disposition", "attachment;filename="+filename);//指定以附件形式进行下载
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.BATCH_EXPORT_EXCEL_FAIL);
        }
    }

    //使用手机号和验证码登录
    @RequestMapping("/getsetmealListByPhoneNumber")
    public Result getsetmealListByPhoneNumber(HttpServletRequest request) {
        try {
            String phoneNumber  = "18511279942";
            phoneNumber = (String)request.getSession().getAttribute("phoneNumber");
            List<Map> map =  memberService.getsetmealListByPhoneNumber(phoneNumber);
            return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEALLIST_FAIL);
        }
    }

}

